package com.dfzt.myutils.common.file;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class TextFileUtil {
    /**
     * 删除文件中指定行范围的文本
     * @param filePath 文件路径
     * @param startRow 起始行
     * @param endRow 结束行
     */
    public static void removeText(String filePath, Integer startRow, Integer endRow){
        if (startRow < 0 || endRow < 0 || startRow > endRow) {
            System.out.println("Invalid row range");
            return;
        }

        String tempFilePath = filePath + ".tmp";

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath))) {
            String line;
            int currentRow = 0;

            while ((line = reader.readLine()) != null) {
                currentRow++;
                if (currentRow < startRow || currentRow > endRow) {
                    writer.write(line);
                    writer.newLine();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 替换原文件为临时文件
        File originalFile = new File(filePath);
        File tempFile = new File(tempFilePath);

        if (originalFile.delete()) {
            if (!tempFile.renameTo(originalFile)) {
                System.out.println("Failed to rename the temporary file to the original file.");
            }
        } else {
            System.out.println("Failed to delete the original file.");
        }
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     */
    public static void deleteFile(String filePath){
        File file = new File(filePath);
        if(file.exists() && file.isFile()){
            boolean delete = file.delete();
            if (delete){
                System.out.println("文件已成功删除:"+filePath);
            }else {
                System.out.println("文件删除失败:"+filePath);
            }
        }else {
            System.out.println("文件不存在或不是一个文件:"+filePath);
        }
    }

    /**
     * 文件按行切割
     * @param linesPerFile 每次切割的行数
     * @param inputFilePath 输入文件路径
     * @param outputDir 输出目录
     */
    public static void splitFile(Integer linesPerFile,String inputFilePath,String outputDir){
        int fileCounter = 1;

        // 提高可用性
        File outputDirectory = new File(outputDir);
        if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
            System.err.println("Failed to create output directory: " + outputDir);
            System.exit(1);
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) {
            String line;
            BufferedWriter currentWriter = null;
            int lineCount = 0;

            while ((line = reader.readLine()) != null) {
                if (lineCount == 0) {
                    System.out.println("正在写入第 "+ fileCounter + " 个文件！");
                    File outputFile = new File(outputDirectory, "part_" + fileCounter + ".sql");
                    currentWriter = new BufferedWriter(new FileWriter(outputFile));
                    fileCounter++;
                }

                currentWriter.write(line);
                currentWriter.newLine();
                lineCount++;

                if (lineCount >= linesPerFile) {
                    currentWriter.close();
                    currentWriter = null;
                    lineCount = 0;
                }
            }

            // 确保最后一个文件也被关闭（如果它存在的话）
            if (currentWriter != null) {
                currentWriter.close();
            }

            System.out.println("File splitting completed successfully.");

        } catch (IOException e) {
            System.err.println("An error occurred while splitting the file: " + e.getMessage());
            // 注意：在这里，如果currentWriter不为null，它应该已经被上面的逻辑关闭了
            // 但是，为了安全起见，你可以在catch块中添加一个额外的检查来关闭它（尽管在这个例子中不是必需的）
        }
    }

    /**
     * 文件按行进行文本替换
     * @param inputFilePath 输入文件路径
     * @param outputFilePath 输出文件路径
     * @param targetText 要替换的文本
     * @param replacementText 替换的文本
     */
    public static void replaceText(String inputFilePath,String outputFilePath,String targetText,String replacementText){
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
            int rownum = 1;

            String line;
            while ((line = reader.readLine()) != null) {
                // 进行文本替换
                line = line.replace(targetText, replacementText);
                // 写入临时文件
                writer.write(line);
                writer.newLine();
                System.out.println("第 " + rownum ++ +" 行" + "处理完成！");
            }

            System.out.println("Text replacement completed successfully.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 按行过滤出符合要求的行
     * @param inputFilePath 输入文件路径
     * @param outputFilePath 输出文件路径
     * @param filterText 过滤的文本
     * @param topN 过滤出符合要求的前topN行
     */
    public static void filterLines(String inputFilePath,String outputFilePath,String filterText,Integer topN){
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
            int rownum = 1;

            String line;
            while ((line = reader.readLine()) != null && rownum <= topN) {
                // 将匹配的行写入临时文件
                if (line.contains(filterText)){
                    // 写入临时文件
                    writer.write(line);
                    writer.newLine();
                    System.out.println("第 " + rownum ++ +" 行" + "处理完成！");
                }
            }

            System.out.println("Text replacement completed successfully.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拷贝文件
     * @param sourceFilePath 源文件路径
     * @param targetFileFolderPath 目标文件夹路径
     */
    public static void copyFile(String sourceFilePath, String targetFileFolderPath) {
        try {
            // 获取源文件的 Path 对象
            Path sourcePath = Paths.get(sourceFilePath);

            // 获取目标文件夹的 Path 对象
            Path targetFolderPath = Paths.get(targetFileFolderPath);

            // 确保目标文件夹存在，如果不存在则创建
            if (!Files.exists(targetFolderPath)) {
                Files.createDirectories(targetFolderPath);
            }

            // 获取目标文件的 Path 对象
            Path targetFilePath = targetFolderPath.resolve(sourcePath.getFileName());

            // 拷贝文件到目标文件夹
            Files.copy(sourcePath, targetFilePath, StandardCopyOption.REPLACE_EXISTING);

            System.out.println("文件已成功拷贝到: " + targetFilePath);
        } catch (IOException e) {
            System.err.println("文件拷贝失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 将字符串写入指定文件，如果文件不存在则新建，如果存在则覆盖
     */
    public static void writeStringToFile(String filePath, String content) {
        try {
            // 创建一个 File 对象，表示要写入的文件路径
            File file = new File(filePath);

            // 创建一个 FileWriter 对象，用于写入文件
            FileWriter writer = new FileWriter(file);

            // 将字符串写入文件
            writer.write(content);

            // 关闭 FileWriter 对象
            writer.close();

            System.out.println("文件写入成功！");
        } catch (IOException e) {
           System.err.println("文件写入失败！");
        }
    }

    /**
     * 统计txt文本文件行数
     */
    public static int countLines(String filePath) {
        int lineCount = 0;

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            while (reader.readLine() != null) {
                lineCount++;
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误: " + e.getMessage());
            e.printStackTrace();
        }

        return lineCount;
    }

}
